package main

import (
	"database/sql"
	"errors"
	"time"
)

type Item struct {
	ID        int       `db:"id"`
	Name      string    `db:"name"`
	Version   int       `db:"version"`
	Timestamp time.Time `db:"timestamp"`
}

func NewItemService(db *sql.DB) *ItemService {
	return &ItemService{
		db: db,
	}
}

type ItemService struct {
	db *sql.DB
}

func (s *ItemService) UpdateItem(item *Item) error {
	var dbVersion int
	err := s.db.QueryRow("SELECT version FROM test_items WHERE id = ?", item.ID).Scan(&dbVersion)
	if err != nil {
		return err
	}
	if dbVersion != item.Version {
		return errors.New("ErrOptimisticLockFailed")
	}

	_, err = s.db.Exec("UPDATE test_items SET name = ?, version = version + 1, timestamp = ? WHERE id = ?", item.Name, time.Now(), item.ID)
	if err != nil {
		return err
	}

	return nil
}
